from PyQt6.QtWidgets import QComboBox,QRadioButton,QWidget,QHBoxLayout,QFileDialog,QMessageBox,QLabel,QVBoxLayout
from PyQt6.QtWidgets import QButtonGroup,QLineEdit,QPushButton
from PyQt6.QtCore import QSize,Qt
from PyQt6.QtGui import QIcon,QPalette,QColor
import os
from utils.Logger import LogPrint
from utils.PdfUtils import pdf2Images,ImageFmt,combineImages,combinePdfImages
from views.WaitPromptBox import WaitPromptBox
from PyQt6.QtCore import QThread, pyqtSignal
from utils import ImageUtils


class RightSettingAreaView(QWidget):


    def __init__(self,parent=None):
        super().__init__(parent=parent)

        self.onRightAreaSettingChangeListener=None
        self.onShowMessage=None
        self.selectedPdfList=None
        self.isCombineLargeImage=False

        self.setupUi()


    def setupUi(self):

        # 设置 QWidget 的背景色
        palette = self.palette()
        palette.setColor(QPalette.ColorRole.Window, QColor("white"))
        self.setPalette(palette)
        self.setAutoFillBackground(True)


        layout=QVBoxLayout()
        layout.setAlignment(Qt.AlignmentFlag.AlignTop)
        layout.addWidget(QLabel("输出方式："))
        outputLayout=QHBoxLayout()
        outputLayout.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.rbEachPage = QRadioButton()      
        # 设置QSS样式
        rbEachPageImageUrl=ImageUtils.getImageStyleURI('each_image_no_check.png')
        rbEachPageCheckImageUrl=ImageUtils.getImageStyleURI('each_image_checked.png')
        self.rbEachPage.setStyleSheet(f"QRadioButton::indicator {{\
                width: 100px;\
                height: 110px;\
            }}\
            QRadioButton::indicator:checked {{\
                image: url({rbEachPageCheckImageUrl});\
            }}\
            QRadioButton::indicator:unchecked {{\
                image: url({rbEachPageImageUrl});\
            }}\
        ")
        self.rbEachPage.setChecked(True)
        self.rbEachPage.clicked.connect(self.onClickedRbEachPage)
        outputLayout.addWidget(self.rbEachPage)

        self.rbComplex = QRadioButton()        
        # 设置QSS样式
        rbComplexImageUrl=ImageUtils.getImageStyleURI('complex_big_image_no_check.png')
        rbComplexCheckImageUrl=ImageUtils.getImageStyleURI('complex_big_image_checked.png')
        self.rbComplex.setStyleSheet(f"QRadioButton::indicator {{\
                width: 100px;\
                height: 110px;\
            }}\
            QRadioButton::indicator:checked {{\
                image: url({rbComplexCheckImageUrl});\
            }}\
            QRadioButton::indicator:unchecked {{\
                image: url({rbComplexImageUrl});\
            }}\
        ")
        self.rbComplex.clicked.connect(self.onClickedRbEachComplex)
        outputLayout.addWidget(self.rbComplex)
        layout.addLayout(outputLayout)

        layout.addSpacing(20)
        layout.addWidget(QLabel("输出范围：(只支持选择单个pdf生效)"))
        self.btnGroupRange = QButtonGroup()
        self.btnGroupRange.setExclusive(True)  
        outputRangeLayout=QHBoxLayout()
        outputRangeLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        rbAllPage = QRadioButton('所有页')   
        rbAllPage.setChecked(True)
        self.btnGroupRange.addButton(rbAllPage,1)
        rbSelectPage = QRadioButton('页码选择')   
        self.btnGroupRange.addButton(rbSelectPage,2)
        self.btnGroupRange.buttonClicked.connect(self.onClickBtnGroupRange)
        outputRangeLayout.addWidget(rbAllPage)
        outputRangeLayout.addWidget(rbSelectPage)
        self.editSelectPage=QLineEdit()
        self.editSelectPage.setPlaceholderText('例:1、3、5-10...')
        self.editSelectPage.setFixedSize(QSize(100,20))
        self.editSelectPage.setEnabled(False)
        self.editSelectPage.returnPressed.connect(self.onReturnPressedEditSelect)
        outputRangeLayout.addWidget(self.editSelectPage)
        layout.addLayout(outputRangeLayout)

        layout.addSpacing(20)
        layout.addWidget(QLabel("输出格式："))
        self.comboFormat=QComboBox()
        self.comboFormat.setStyleSheet("QWidget { border-radius: 20px; }")
        self.comboFormat.setFixedSize(QSize(100,30))
        self.comboFormat.addItem("JPG")
        self.comboFormat.addItem("PNG")
        #self.comboFormat.addItem("PPM")
        self.comboFormat.currentIndexChanged.connect(self.onComboboxFormatChanged)
        layout.addWidget(self.comboFormat)

        layout.addSpacing(20)
        layout.addWidget(QLabel("输出品质："))
        self.comboQuality=QComboBox()
        self.comboQuality.setStyleSheet("QWidget { border-radius: 20px; }")
        self.comboQuality.setFixedSize(QSize(100,30))
        self.comboQuality.addItem("标清")
        self.comboQuality.addItem("高清")
        self.comboQuality.currentIndexChanged.connect(self.onComboboxFormatChanged)
        layout.addWidget(self.comboQuality)

        layout.addSpacing(20)
        layout.addWidget(QLabel("输出目录："))
        outputDirLayout=QHBoxLayout()
        outputDirLayout.setAlignment(Qt.AlignmentFlag.AlignLeft)
        self.comboDir=QComboBox()
        self.comboDir.setStyleSheet("QWidget { border-radius: 20px; }")
        self.comboDir.setFixedSize(QSize(100,30))
        self.comboDir.addItem("源文件目录")
        self.comboDir.addItem("自定义目录")
        self.comboDir.currentIndexChanged.connect(self.onComboboxSelectDirChanged)
        self.comboDir.hide()
        outputDirLayout.addWidget(self.comboDir)
        

        self.editDir=QLineEdit()
        self.editDir.setEnabled(False)
        localPath = os.path.join(os.environ['LOCALAPPDATA'], '')
        self.editDir.setText(localPath)
        outputDirLayout.addWidget(self.editDir)
        self.btnSelectDir=QPushButton()
        self.btnSelectDir.setIcon(ImageUtils.getQIcon('icon_add_file.svg'))
        self.btnSelectDir.clicked.connect(self.onClickedBtnSelectDir)
        self.btnSelectDir.setFlat(True)
        outputDirLayout.addWidget(self.btnSelectDir)
        layout.addLayout(outputDirLayout)

        layout.addSpacing(20)
        self.btnExportFile= QPushButton()
        self.btnExportFile.setFixedSize(QSize(100,30))
        self.btnExportFile.setText("导出图片")
        self.btnExportFile.setIcon(ImageUtils.getQIcon('icon_export.svg'))
        self.btnExportFile.clicked.connect(self.onClickBtnExportFile)
        layout.addWidget(self.btnExportFile,alignment=Qt.AlignmentFlag.AlignCenter)
       
        #self.setStyleSheet("background-color:red")
        self.setLayout(layout)

    #设置区域改变监听
    def setOnRightAreaSettingChangeListener(self,onRightAreaSettingChangeListener):
        self.onRightAreaSettingChangeListener=onRightAreaSettingChangeListener

    def setOnShowMessage(self,onShowMessage):
        self.onShowMessage=onShowMessage

    #设置选中pdf文件列表
    def setSelectedPdfList(self,selectedPdfList):
        self.selectedPdfList=selectedPdfList

    #右侧点击输出方式---逐页输出
    def onClickedRbEachPage(self,checked):
        LogPrint.info('onClickedRbEachPage',checked)
        self.isCombineLargeImage = False
        if self.onRightAreaSettingChangeListener:
            self.onRightAreaSettingChangeListener(isCombineLargeImage=False)

    #右侧点击输出方式---合成长图
    def onClickedRbEachComplex(self,checked):
        LogPrint.info('onClickedRbEachComplex',checked)
        self.isCombineLargeImage = True
        if self.onRightAreaSettingChangeListener:
            self.onRightAreaSettingChangeListener(isCombineLargeImage=True)

    #设置输出范围模块是否可用
    def setInputRangeEnable(self,enable):
        # self.btnGroupRange.button(1).setCheckable(True)
        # self.btnGroupRange.button(2).setCheckable(False)
        self.editSelectPage.setEnabled(False)

        if enable:
            self.btnGroupRange.button(1).setEnabled(True)
            self.btnGroupRange.button(2).setEnabled(True)
        else :
            self.btnGroupRange.button(1).setEnabled(False)
            self.btnGroupRange.button(2).setEnabled(False)
        pass
    
    #点击选择所有或者页码选择checkbox
    def onClickBtnGroupRange(self,button):
        LogPrint.info(f'onClickBtnGroupRange {self.btnGroupRange.checkedButton().text()} Clicked,checkedId:{self.btnGroupRange.checkedId()}')
        LogPrint.info('event:',button.text())
        checkedId=self.btnGroupRange.checkedId()
        if checkedId==2:
            self.editSelectPage.setEnabled(True)
            if self.onRightAreaSettingChangeListener:
                self.onRightAreaSettingChangeListener(selectAllPageNo=False)

        else:
            #点击全选
            self.editSelectPage.setText('')
            self.editSelectPage.setEnabled(False)

            if self.onRightAreaSettingChangeListener:
                self.onRightAreaSettingChangeListener(selectAllPageNo=True)

    #页码输入框回车处理
    def onReturnPressedEditSelect(self):

        pageNoList=self.getEditSelectPageNo()
        LogPrint.info(pageNoList)
        if self.onRightAreaSettingChangeListener:
                self.onRightAreaSettingChangeListener(selectPageNoList=pageNoList)

    #获取页码选择框中的页码列表
    def getEditSelectPageNo(self):
        text=self.editSelectPage.text()
        pageNoList=[]
        if '、' in str(text):
            numbers=str(text).split('、')
            for num in numbers:
                if num.isdigit():
                    pageNoList.append(int(num))
                elif '-' in str(num) :
                    numbers2=str(num).split('-')
                    if numbers2[0].isdigit() and numbers2[1].isdigit():
                        for num2 in range(int(numbers2[0]),int(numbers2[1])+1):
                            pageNoList.append(num2)
        elif '-' in str(text) :
            numbers=str(text).split('-')
            if numbers[0].isdigit() and numbers[1].isdigit():
                for num in range(int(numbers[0]),int(numbers[1])+1):
                    pageNoList.append(num)
        elif text.isdigit():
            pageNoList.append(int(text))
        return pageNoList
    
    #获取页码选择框中的页码起止列表（如：1、3-5，返回[[1,1],[3,5]]）
    def getEditSelectPageStartEndList(self):
        #获取选择页面
        if self.btnGroupRange.checkedButton()==2: 
            return None
        text=self.editSelectPage.text()
        pageStartEndList=[]
        if '、' in str(text):
            numbers=str(text).split('、')
            for num in numbers:
                if num.isdigit():
                    startEnd=[]
                    startEnd.append(int(num))
                    startEnd.append(int(num))
                    pageStartEndList.append(startEnd)
                elif '-' in str(num) :
                    numbers2=str(num).split('-')
                    if numbers2[0].isdigit() and numbers2[1].isdigit():
                        startEnd=[]
                        startEnd.append(int(numbers2[0]))
                        startEnd.append(int(numbers2[1]))
                        pageStartEndList.append(startEnd)
        elif '-' in str(text) :
            numbers=str(text).split('-')
            if numbers[0].isdigit() and numbers[1].isdigit():
                startEnd=[]
                startEnd.append(int(numbers[0]))
                startEnd.append(int(numbers[1]))
                pageStartEndList.append(startEnd)
        elif text.isdigit():
            startEnd=[]
            startEnd.append(int(text))
            startEnd.append(int(text))
            pageStartEndList.append(startEnd)
        return pageStartEndList

    def onComboboxFormatChanged(self,index):
        LogPrint.info('onComboboxFormatChanged',self.comboFormat.currentText(),index)

    #选择框，选中自定义目录时，显示选择目录按钮
    def onComboboxSelectDirChanged(self,index):
        LogPrint.info('onComboboxFormatChanged',self.comboFormat.currentText(),index)
        if index==0:
            self.btnSelectDir.hide()
        else:
            self.btnSelectDir.show()


    #选择保存目录按钮点击
    def onClickedBtnSelectDir(self,event):
        # 使用 QFileDialog 打开一个目录对话框，并获取选择的目录路径
        directory = QFileDialog.getExistingDirectory(self, "选择目录", "/")
        if directory:
            LogPrint.info(directory)  # 打印选择的目录路径
            self.editDir.setText(directory)

    #导出文件
    def onClickBtnExportFile(self,event):
        imageExportType=0
        if self.rbComplex.isChecked():
            imageExportType=1
        pageNoList=self.getEditSelectPageNo()
        imageQuality=self.comboQuality.currentText()
        imageFormat=self.comboFormat.currentText()
        imageSavePath=self.editDir.text()
        pageStartEndList=self.getEditSelectPageStartEndList()
        LogPrint.info(f'imageExportType:{imageExportType},pageNoList:{pageNoList},imageQuality:{imageQuality},imageFormat:{imageFormat},imageSavePath:{imageSavePath}')
        LogPrint.info(f'pageStartEndList:{pageStartEndList}')
        if self.onShowMessage and self.selectedPdfList is None or len(self.selectedPdfList)==0:
            LogPrint.info('未选择pdf文件')
            self.onShowMessage('未选择pdf文件')
            return
        paramQualit=0
        if imageQuality=='高清':
            paramQualit=1
        paramFmt=ImageFmt.JPG
        if imageFormat=='PNG':
            paramFmt=ImageFmt.PNG
        elif imageFormat=='PPM':
            paramFmt=ImageFmt.PPM

        self.waitBox=WaitPromptBox(self,'正在导出文件')
        self.waitBox.show()

        self.startThreadExport(self.isCombineLargeImage,self.selectedPdfList,imageSavePath,pageNoList,paramQualit,paramFmt,pageStartEndList)

        

    def startThreadExport(self,isCombineLargeImage,selectedPdfList,imageSavePath,pageNoList,paramQualit,paramFmt,pageStartEndList):
        # 使用QThread
        dataParam=[]
        dataParam.append(isCombineLargeImage)
        dataParam.append(selectedPdfList)
        dataParam.append(imageSavePath)
        dataParam.append(pageNoList)
        dataParam.append(paramQualit)
        dataParam.append(paramFmt)
        dataParam.append(pageStartEndList)
        LogPrint.debug('startThreadExport data',dataParam)
        thread = MyThread(dataParam)
        thread.signal.connect(self.threadExportFinish)
        thread.start()

    def threadExportFinish(self,result):
        self.waitBox.close()
        QMessageBox.information(None,'系统提示','导出完成\n文件名：'+result)



class MyThread(QThread):
    signal = pyqtSignal(str)

    def __init__(self,data=None):
        super().__init__()
        self.data=data

    def run(self):
        isCombineLargeImage=self.data[0]
        selectedPdfList=self.data[1]
        imageSavePath=self.data[2]
        pageNoList=self.data[3]
        paramQualit=self.data[4]
        paramFmt=self.data[5]
        pageStartEndList=self.data[6]
        LogPrint.debug('run data',self.data)
        result = ""
        if isCombineLargeImage:
            #combineImages(selectedPdfList,imageSavePath,pageNoList)
            result=combinePdfImages(selectedPdfList,paramQualit,imageSavePath,paramFmt,pageNoList,pageStartEndList)
        else :
            for  pdfPath in selectedPdfList:          
                tempDirList=pdf2Images(pdfPath,paramQualit,imageSavePath,paramFmt,pageStartEndList)
                for tempDir in tempDirList:
                    result+=tempDir
                    result+=',\n'
        self.signal.emit(result)


    